package com.ruoyi.web.controller.word;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.ErrorCode;
import com.ruoyi.common.utils.RandomUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.baidu.TransWebApi;
import com.ruoyi.common.utils.file.QiniuImageUploader;
import com.ruoyi.common.utils.youdao.FanyiV3Util;
import com.ruoyi.common.domain.word.*;
import com.ruoyi.word.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.*;


@RestController
@RequestMapping("/api/baidu/word/ext")
public class BaiduWordExtController extends BaseController {

    @Autowired
    private BaiduWordExtService biz;

    @Autowired
    private ICommonWordService wordService;

    @Autowired
    private ICommonWordPronounceService pronounceService;

    @Autowired
    private ICommonWordFormService formService;

    @Autowired
    private ICommonWordSentenceService sentenceService;


    int errorCount = 1;

    @PostMapping("/save")
    public BaiduWordExt saveObj(@RequestParam(defaultValue = "a", required = false) String query) {
        try {
            BaiduWordExt ext = biz.getByName(query);
            if (ext != null) {
                if(ext.getEg() != null) {
                    System.out.println("数据已存在: " + query);
                    return ext;
                }
                biz.deleteBook(ext);
            }
            JSONObject data = TransWebApi.trans(query);
            if (data == null || !data.containsKey("trans_result")) {
                errorCount++;
                System.out.println("接口查询失败: "+ query);
            }
            JSONObject trans_result = data.getJSONObject("trans_result");
            BaiduWordExt word = new BaiduWordExt();
            word.setId(RandomUtil.getRandomNum(8));
            word.setFrom(trans_result.getString("from"));
            word.setTo(trans_result.getString("to"));
            word.setType(trans_result.getInteger("type"));
            word.setPhonetic(trans_result.getJSONArray("phonetic"));
            word.setKeywords(trans_result.getJSONArray("keywords"));

            JSONObject dd = trans_result.getJSONArray("data").getJSONObject(0);
            word.setSrc(dd.getString("src"));
            word.setDst(dd.getString("dst"));
            word.setDict(data.getJSONObject("dict_result"));
            if(data.containsKey("liju_result")) {
                word.setEg(data.getJSONObject("liju_result"));
            }
            System.out.println(word.getSrc() + " ==> " + JSON.toJSONString(word.getDict()));
            biz.saveObj(word);
            return word;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Async
    public void saveObjSync(String query) {
        try {
            if (biz.getByName(query) != null) {
                System.out.println(ErrorCode.ALREADY_EXISTS);
                return;
            }
            JSONObject data = TransWebApi.trans(query);
            if (data == null || !data.containsKey("trans_result")) {
                errorCount++;
                System.out.println("接口查询失败: "+ query);
                return;
            }
            JSONObject trans_result = data.getJSONObject("trans_result");
            BaiduWordExt word = new BaiduWordExt();
            word.setId(RandomUtil.getRandomNum(8));
            word.setFrom(trans_result.getString("from"));
            word.setTo(trans_result.getString("to"));
            word.setType(trans_result.getInteger("type"));
            word.setPhonetic(trans_result.getJSONArray("phonetic"));

            JSONObject dd = trans_result.getJSONArray("data").getJSONObject(0);
            word.setSrc(dd.getString("src"));
            word.setDst(dd.getString("dst"));

            word.setDict(data.getJSONObject("dict_result"));
            biz.saveObj(word);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

//    @GetMapping("/saveAll")
//    public String saveAll() {
//        List<Words> allWords = biz.findAllWords();
//        List<String> wordList = new ArrayList<>();
//        allWords.stream().forEach(w -> {
//            if(wordList.contains(w.getWord())) {
//                System.out.println("repeat word: " + w.getWord());
//                biz.deleteWords(w);
//                return;
//            }
//            wordList.add(w.getWord());
//        });
//        System.out.println("word size: "+ wordList.size());
//        for (int i = 0; i < wordList.size(); i++) {
//            if(errorCount > 50000) {
//                errorCount = 0;
//                return "error";
//            }
//            BaiduWordExt baiduWordExt = saveObj(wordList.get(i));
//            if(baiduWordExt != null) {
//                System.out.println(i + "-->" + baiduWordExt.getSrc());
//            }
//        }
//        return "保存成功";
//    }

    // @GetMapping("/saveAllFromEc")
    // @Scheduled(fixedDelay = 1000*60*60*60)
    public String saveAllFromEc() {
        int currentPage = 1;
        int pageSize = 1000;
        while (true) {
            List<EcDict> allWords = biz.findAllEcDictByPage(currentPage, pageSize);
            List<String> wordList = new ArrayList<>();
            allWords.forEach(w -> {
                if (wordList.contains(w.getWord())) {
                    System.out.println("repeat word: " + w.getWord());
                    return;
                }
                wordList.add(w.getWord());
            });
            System.out.println("word size: " + wordList.size());
            for (int i = 0; i < wordList.size(); i++) {
                if (errorCount > 50000) {
                    errorCount = 0;
                    return "error";
                }
                // 先排除词组
//                if(StringUtils.contains(wordList.get(i), " ")) {
//                    continue;
//                }
                System.out.print(i + ": ");
                BaiduWordExt baiduWordExt = saveObj(wordList.get(i));
//                if (baiduWordExt != null) {
//                    System.out.println(i + ": " + baiduWordExt.getSrc() + "--> " + baiduWordExt.getDst());
//                }
            }
            if(allWords.size() < pageSize) {
                return "保存成功";
            }
            currentPage++;
        }
    }

    @GetMapping("/findAll")
    public List<BaiduWordExt> findAll() {
        return biz.findAll();
    }

    @GetMapping("/findOne")
    public BaiduWordExt findOne(@RequestParam Long id) {
        return biz.getBookById(id);
    }

    @GetMapping("/findOneByName")
    public BaiduWordExt findOneByName(@RequestParam String name) {
        BaiduWordExt wordExt = biz.getByName(name);
        if(wordExt == null) {
            return saveObj(name);
        }
        return wordExt;
    }

    @PostMapping("/update")
    public String update(@RequestBody BaiduWordExt book) {
        return biz.updateBook(book);
    }

    @PostMapping("/delOne")
    public String delOne(@RequestBody BaiduWordExt book) {
        return biz.deleteBook(book);
    }

    @GetMapping("/delById")
    public String delById(@RequestParam Long id) {
        return biz.deleteBookById(id);
    }

    @GetMapping("/findlikes")
    public List<BaiduWordExt> findByLikes(@RequestParam String search) {
        return biz.findByLikes(search);
    }

    @GetMapping("/removeDuplicateData")
    public String removeDuplicateData(){
        return biz.removeDuplicateData();
    }

    @GetMapping("/init/data")
    public String initData() {
        System.out.println(new Date());
        List<EcDict> allWords = biz.findAllEcDictByPage(1, Integer.MAX_VALUE);
        System.out.println(allWords.size());
        System.out.println(new Date());
        // List<String> wordList = new ArrayList<>();
        Map<String, String> wordList = new HashMap<>();
        allWords.forEach(w -> {
            if (wordList.containsKey(w.getWord())) {
                System.out.println("repeat word: " + w.getWord());
                return;
            }
            wordList.put(w.getWord(), "");
        });
        System.out.println("word size: " + wordList.size());

        String[] wordFirstList = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
        for (String wf : wordFirstList) {
            new Thread(() -> {
                System.out.println("线程1---------");
                // 循环单词列表，拉取数据
                for (String word : wordList.keySet()) {
                    word = word.trim();
                    //StringUtils.contains(word, " ") ||  去掉部分代码，使得词组可以正常录入
                    if (StringUtils.contains(word, "-")
                            || StringUtils.isNumeric(word)) {
                        continue;
                    }
                    String wordFirst = word.substring(0, 1).toLowerCase();//全部转换小写，获得单词首字母
                    if (StringUtils.equals(wordFirst, wf)) {
                        // bus
                        System.out.println(word + "=========" + wf);
                        moveWord(word);
                    }
                }
            }).start();
        }

        return "完成";
    }

    //    @GetMapping("/init/data")
    public void moveWord(String words){
//        words = "alkynol";
        try {
            //查询mongodb数据库数据，测试使用一条
            BaiduWordExt apple = saveObj(words);
            //判断单词是否存在common_word表中
            CommonWord word = wordService.findByWord(words);
            if (word != null){//如果单词存在与common_word表中，去判断发音表是否存在对应的数据
                List<CommonWordPronounce> pronounce = pronounceService.findByWid(word.getId());
                if (pronounce == null ) {//如果发音为空（发音不全没做处理），下面根据单词执行脚本进行保存
                    youdaoSave(word);
                }
            }else {//如果等于空，那么说明词库里面没有这个单词
                if (apple.getDict() == null){
                    return;
                }
                CommonWord word2 =build(apple);
                wordService.save(word2);
                //保存发音
                youdaoSave(word2);
                buildAndSave(apple, word2.getId());//保存构建例句
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 解析构建例句并保存
     * @param ext
     * @param wid
     */
    private void buildAndSave(BaiduWordExt ext, Long wid){
        if (ext.getEg() == null || String.valueOf(ext.getEg().get("double")) == null){
            return;
        }
        JSONArray doubles = (JSONArray) JSONArray.parse(String.valueOf(ext.getEg().get("double")));

        int size  = 1;
        if (doubles.size() > 3){
            size = 3;
        }else {
            size = doubles.size();
        }
        int sum = 0;
        for (int i = 0 ; i< size; i ++){//30ge
            CommonWordSentence sentence = new CommonWordSentence();
            JSONArray jsonArray = doubles.getJSONArray(i);
            StringBuffer sb_eng = new StringBuffer();
            StringBuffer sb_chain = new StringBuffer();
            String from = "";
            sum ++;
            for (int j = 0 ; j < jsonArray.size(); j ++){//4ge
                if (j == 0){
                    JSONArray jsonArray_1 = jsonArray.getJSONArray(j);
                    for (int m = 0 ; m < jsonArray_1.size(); m++){
                        JSONArray jsonArray_11 = jsonArray_1.getJSONArray(m);
                        sb_eng.append(jsonArray_11.get(0)).append(" ");
                    }
                }
                if (j == 1){
                    JSONArray jsonArray_1 = jsonArray.getJSONArray(j);
                    for (int m = 0 ; m < jsonArray_1.size(); m++){
                        JSONArray jsonArray_11 = jsonArray_1.getJSONArray(m);
                        sb_chain.append(jsonArray_11.get(0));
                    }
                }
                if (j == 2){
                    from = jsonArray.get(2).toString();
                }
            }
            System.out.println("英语："+sb_eng);
            System.out.println("中文："+sb_chain);
            System.out.println("来源："+from);
            sentence.setAddTime(new Date());
            sentence.setSort(sum);
            sentence.setContent(sb_eng.toString());
            sentence.setPh(sb_chain.toString());
            sentence.setSource(from);
            sentence.setSid(0L);
            sentence.setWid(wid);
            sentence.setAddUid(-1L);//转移过来的设置-1
            //保存
            sentenceService.save(sentence);
        }

    }

    /**
     * 通过BaiduWordExt对象构建CommonWord
     * @param ext
     * @return
     */
    private CommonWord build(BaiduWordExt ext){

        JSONArray jsonArray = ext.getDict().getJSONObject("simple_means").getJSONArray("symbols").getJSONObject(0).getJSONArray("parts");
        String sim = "";

        //获取简单释义
        for (int i = 0 ; i< jsonArray.size(); i ++){
            String s1 = jsonArray.getJSONObject(i).getString("part");
            if (s1 == null){
                s1 = "";
            }
//            List<String> s2 = Collections.singletonList(jsonArray.getJSONObject(i).getString("means"));
            String jsonS2 = jsonArray.getJSONObject(i).getString("means");
            List<String> parse =JSONArray.parseArray(jsonS2, String.class);
            sim =  s1 + parse.get(0);
        }
        String com = "";
        //获取完整释义
        for (int i = 0 ; i< jsonArray.size(); i ++){
            String s1 = jsonArray.getJSONObject(i).getString("part");
            if (s1 == null){
                s1 = "";
            }
            List<String> s2 =JSONArray.parseArray(jsonArray.getJSONObject(i).getString("means"), String.class);
            StringBuffer sb = new StringBuffer();
            for (String str:s2) {
                sb.append(str).append(",");
            }
            com =  s1 + sb.toString().substring(0, sb.length() - 1);
        }

        CommonWord word = new CommonWord();
        word.setName(ext.getSrc());
        word.setAddTime(new Date());
        word.setUpdateTime(word.getAddTime());
        word.setUpdateUid(-1L);//系统导入设置-1
        word.setSimplePh(sim);
        word.setCompletePh(com);

        return word;
    }

    private void youdaoSave(CommonWord word) throws IOException {

        String result = FanyiV3Util.trans(word.getName());
        // String result = "{\"returnPhrase\":[\"zoom\"],\"RequestId\":\"ef0e21a5-4d85-4947-8338-3ef24f5df945\",\"query\":\"zoom\",\"errorCode\":\"0\",\"l\":\"en2zh-CHS\",\"tSpeakUrl\":\"http://openapi.youdao.com/ttsapi?q=%E5%8F%98%E7%84%A6&langType=zh-CHS&sign=EAFC7F3C767E2DE5F3EE2F84E338F7D1&salt=1591088244204&voice=4&format=mp3&appKey=006f134b6f962944\",\"web\":[{\"value\":[\"缩放\",\"变焦\",\"超人集中营\",\"放大镜\"],\"key\":\"Zoom\"},{\"value\":[\"缩小\",\"缩小显示\",\"画面拉远\",\"放大\"],\"key\":\"zoom out\"},{\"value\":[\"变焦环\",\"变焦距圈\",\"变焦距环\"],\"key\":\"ZOOM RING\"}],\"translation\":[\"变焦\"],\"dict\":{\"url\":\"yddict://m.youdao.com/dict?le=eng&q=zoom\"},\"webdict\":{\"url\":\"http://m.youdao.com/dict?le=eng&q=zoom\"},\"basic\":{\"exam_type\":[\"高中\",\"GRE\",\"考研\"],\"us-phonetic\":\"zuːm\",\"phonetic\":\"zuːm\",\"uk-phonetic\":\"zuːm\",\"wfs\":[{\"wf\":{\"name\":\"复数\",\"value\":\"zooms\"}},{\"wf\":{\"name\":\"过去式\",\"value\":\"zoomed\"}},{\"wf\":{\"name\":\"过去分词\",\"value\":\"zooming\"}},{\"wf\":{\"name\":\"现在分词\",\"value\":\"zooming\"}},{\"wf\":{\"name\":\"第三人称单数\",\"value\":\"zooms\"}}],\"uk-speech\":\"http://openapi.youdao.com/ttsapi?q=zoom&langType=en&sign=3EE987B12A2F827A6C8B5E30AC66D514&salt=1591088244204&voice=5&format=mp3&appKey=006f134b6f962944\",\"explains\":[\"v. （尤指汽车、飞机等）疾行；（价格、费用等）急剧增长，猛涨；（使镜头或摄影机）推近或拉远\",\"n. （车辆等）疾驰的声音，嗡嗡声；变焦摄影；急速上升\",\"int. （用于表示突然的快速移动）嗖地\"],\"us-speech\":\"http://openapi.youdao.com/ttsapi?q=zoom&langType=en&sign=3EE987B12A2F827A6C8B5E30AC66D514&salt=1591088244204&voice=6&format=mp3&appKey=006f134b6f962944\"},\"isWord\":true,\"speakUrl\":\"http://openapi.youdao.com/ttsapi?q=zoom&langType=en&sign=3EE987B12A2F827A6C8B5E30AC66D514&salt=1591088244204&voice=4&format=mp3&appKey=006f134b6f962944\"}";
        System.out.println(result);
        JSONObject jo = JSON.parseObject(result);
        if(jo == null || jo.getJSONObject("basic") == null) {
            System.out.println("word err: " + word.getName());
            return;
        }
        JSONObject basic = jo.getJSONObject("basic");
        CommonWordPronounce pronounce = new CommonWordPronounce();
        pronounce.setAddTime(new Date());
        pronounce.setWid(word.getId());
        pronounce.setType(1);
        pronounce.setContent(basic.getString("uk-phonetic"));
        pronounce.setAudio(uploadToQiniu(basic.getString("uk-speech"), word.getName(), "1"));

        CommonWordPronounce pronounce2 = new CommonWordPronounce();
        pronounce2.setAddTime(new Date());
        pronounce2.setWid(word.getId());
        pronounce2.setType(2);
        pronounce2.setContent(basic.getString("us-phonetic"));
        pronounce2.setAudio(uploadToQiniu(basic.getString("us-speech"), word.getName(), "2"));
        System.out.println(JSON.toJSONString(pronounce));
        System.out.println(JSON.toJSONString(pronounce2));
        pronounceService.saveByWord(word, new ArrayList(){
            private static final long serialVersionUID = -1L;
            {add(pronounce); add(pronounce2);}
        });

        // 获取单词其他形式
        JSONArray ja = basic.getJSONArray("wfs");
        if(ja != null) {
            List<CommonWordForm> list = new ArrayList<>();
            for (Object wf: ja) {
                JSONObject wfo = ((JSONObject)wf).getJSONObject("wf");
                CommonWordForm form = new CommonWordForm();
                form.setAddTime(new Date());
                form.setWid(word.getId());
                form.setWord(word.getName());
                form.setName(wfo.getString("name"));
                form.setValue(wfo.getString("value"));
                list.add(form);
            }
            formService.saveByWord(word, list);
        }

    }

    private static String uploadToQiniu(String url, String word, String type) throws IOException {
        url = "https://dict.youdao.com/dictvoice?audio=" + word + "&type=" + type;
        String fileName = "xbky/dms/pronounce/" + type + "/" + word;

        QiniuImageUploader.MyRet ret = QiniuImageUploader.upload(FanyiV3Util.getByteFromUrl(url), fileName, "bukaa-common");
        System.out.println(ret.url.replaceAll("%2F", "/"));
        return ret.url.replaceAll("%2F", "/");
    }


}